<template>
  <view class="upload-container">
	<view class="form-item">
	  <text class="label">视频列表</text>
	  <input v-model="form.videoslist" placeholder="请输入视频列表" class="input" />
	</view>
	
    <view class="form-item">
      <text class="label">视频标题</text>
      <input v-model="form.title" placeholder="请输入视频标题" class="input" />
    </view>
    
    <view class="form-item">
      <text class="label">视频描述</text>
      <textarea v-model="form.description" placeholder="请输入视频描述" class="textarea" />
    </view>
    
    <view class="form-item">
      <text class="label">选择视频文件</text>
      <button @click="chooseVideo" class="upload-btn">选择视频</button>
      <text v-if="videoFile" class="file-name">{{ videoFile.name }}</text>
    </view>
    
    <view class="form-item">
      <text class="label">选择封面图片</text>
      <button @click="chooseCover" class="upload-btn">选择封面</button>
      <text v-if="coverFile" class="file-name">{{ coverFile.name }}</text>
    </view>
    
    <button @click="submit" class="submit-btn" :disabled="uploading">
      {{ uploading ? '上传中...' : '提交上传' }}
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: '',
        description: '',
		videoslist: '',
        user_id: uni.getStorageSync('user').id // 实际应用中应从用户登录信息获取
      },
      videoFile: null,
      coverFile: null,
      uploading: false
    }
  },
  methods: {
    chooseVideo() {
	  uni.chooseVideo({
		sourceType: ['album'], // 只从相册选择
		compressed: true,
		maxDuration: 300, // 5分钟限制
		success: (res) => {
		  this.videoFile = {
			name: res.tempFilePath.split('/').pop() || `video_${Date.now()}.mp4`,
			path: res.tempFilePath,
			size: res.size,
			duration: res.duration
		  };
		  console.log('已选择视频:', this.videoFile);
		},
		fail: (err) => {
		  console.error('选择视频失败:', err);
		  let errMsg = '选择视频失败';
		  if (err.errMsg.includes('cancel')) {
			errMsg = '已取消选择';
		  }
		  uni.showToast({
			title: errMsg,
			icon: 'none'
		  });
		}
	  });
	},

	// 改进后的选择封面方法
	chooseCover() {
	  uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album'],
		success: (res) => {
		  this.coverFile = {
			name: 'cover_' + Date.now() + '.jpg',
			path: res.tempFilePaths[0]
		  };
		  console.log('已选择封面:', this.coverFile);
		},
		fail: (err) => {
		  console.error('选择封面失败:', err);
		  let errMsg = '选择封面失败';
		  if (err.errMsg.includes('cancel')) {
			errMsg = '已取消选择';
		  }
		  uni.showToast({
			title: errMsg,
			icon: 'none'
		  });
		}
	  });
	},
	 async blobUrlToFile(filePath, fileName) {
	   try {
	     // #ifdef H5
	     // 仅H5环境使用fetch
	     if (filePath.startsWith('blob:')) {
	       const response = await fetch(filePath);
	       const blob = await response.blob();
	       return new File([blob], fileName, { type: blob.type });
	     }
	     // #endif
	     
	     // 非H5环境或非Blob URL直接返回文件对象
	     return {
	       name: fileName,
	       uri: filePath,
	       type: this.getFileType(filePath)
	     };
	   } catch (error) {
	     console.error('文件处理失败:', error);
	     throw new Error('文件处理失败');
	   }
	 },
	 
	 getFileType(filePath) {
	   const ext = filePath.split('.').pop().toLowerCase();
	   const videoTypes = ['mp4', 'mov', 'avi', 'mkv'];
	   const imageTypes = ['jpg', 'jpeg', 'png', 'gif'];
	   
	   if (videoTypes.includes(ext)) return 'video/' + ext;
	   if (imageTypes.includes(ext)) return 'image/' + ext;
	   return 'application/octet-stream';
	 },
     async submit() {
          // 更完善的验证
          if (!this.form.title || this.form.title.trim().length < 2) {
            uni.showToast({
              title: '请输入至少2个字的视频标题',
              icon: 'none'
            });
            return;
          }
          
          if (!this.videoFile?.path) {
            uni.showToast({
              title: '请先选择视频文件',
              icon: 'none'
            });
            return;
          }
          
          if (!this.coverFile?.path) {
            uni.showToast({
              title: '请先选择封面图片',
              icon: 'none'
            });
            return;
          }
          
          // 检查文件大小 (示例值，根据实际需求调整)
          if (this.videoFile.size > 100 * 1024 * 1024) { // 100MB限制
            uni.showToast({
              title: '视频文件不能超过100MB',
              icon: 'none'
            });
            return;
          }
          
          this.uploading = true;
          uni.showLoading({
            title: '上传中...',
            mask: true
          });
          
     try {
		// 1. 先上传视频文件
		const videoUpload = await new Promise((resolve, reject) => {
		  const task = uni.uploadFile({
			url: 'http://192.168.1.188/api/uploadVideo.php',
			filePath: this.videoFile.path,
			name: 'video',
			formData: {
			  action: 'upload_video',
			  filename: this.videoFile.name,
			  title: this.form.title,
			  description: this.form.description,
			  videoslist: this.form.videoslist,
			  user_id: this.form.user_id
			},
			success: resolve,
			fail: reject
		  });
		  
		  task.onProgressUpdate((res) => {
			console.log('视频上传进度:', res.progress);
		  });
		});

		// 2. 上传封面文件
		const coverUpload = await new Promise((resolve, reject) => {
		  const task = uni.uploadFile({
			url: 'http://192.168.1.188/api/uploadVideo.php',
			filePath: this.coverFile.path,
			name: 'cover',
			formData: {
			  action: 'upload_cover',
			  filename: this.coverFile.name
			},
			success: resolve,
			fail: reject
		  });
		  
		  task.onProgressUpdate((res) => {
			console.log('封面上传进度:', res.progress);
		  });
		});

		// 解析响应
		const parseResponse = (res) => {
		  try {
			const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
			if (data.code !== 200) {
			  throw new Error(data.message || '上传失败');
			}
			return data;
		  } catch (e) {
			console.error('响应解析错误:', e);
			throw new Error('响应解析失败');
		  }
		};

		const videoData = parseResponse(videoUpload);
		const coverData = parseResponse(coverUpload);

		// 3. 关联视频和封面
		const associateRes = await uni.request({
		  url: 'http://192.168.1.188/api/uploadVideo.php',
		  method: 'POST',
		  header: {
			'Content-Type': 'application/x-www-form-urlencoded'
		  },
		  data: {
			action: 'associate',
			file_path: videoData.file_path,
			cover_path: coverData.cover_path,
			title: this.form.title,
			description: this.form.description,
			videoslist: this.form.videoslist,
			user_id: this.form.user_id
		  }
		});

		const associateData = parseResponse(associateRes);

		uni.showToast({ title: '上传成功', icon: 'success' });
		setTimeout(() => uni.navigateBack(), 1500);

	  } catch (error) {
		console.error('上传出错:', error);
		uni.showToast({
		  title: error.message || '上传失败',
		  icon: 'none',
		  duration: 3000
		});
	  } finally {
		this.uploading = false;
		uni.hideLoading();
	  }
   
    }
  }
}
</script>

<style>
.upload-container {
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.input, .textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.textarea {
  height: 80px;
}

.upload-btn {
  background-color: #f0f0f0;
  color: #333;
  font-size: 14px;
  padding: 8px 12px;
}

.file-name {
  margin-left: 10px;
  font-size: 12px;
  color: #666;
}

.submit-btn {
  margin-top: 20px;
  background-color: #007aff;
  color: white;
  padding: 12px;
  border-radius: 4px;
}

.submit-btn[disabled] {
  background-color: #ccc;
}
</style>